<script setup lang="ts">
import { computed, ref, watch } from 'vue';
import { createSourceData, updateSourceData } from '@/service/api/source-data';

const props = defineProps<{
  visible: boolean;
  record: Api.SourceData.SourceData | null;
}>();

const emit = defineEmits<{
  (e: 'update:visible', visible: boolean): void;
  (e: 'ok'): void;
}>();

const formState = ref<Partial<Api.SourceData.SourceData>>({});

const isEdit = computed(() => Boolean(props.record?.id));

watch(
  () => props.record,
  newVal => {
    formState.value = newVal ? { ...newVal } : {};
  }
);

/** 处理确认 */
async function handleOk() {
  try {
    if (isEdit.value && props.record?.id) {
      await updateSourceData(props.record.id, formState.value);
    } else {
      await createSourceData(formState.value);
    }
    window.$message?.success(isEdit.value ? '更新成功' : '创建成功');
    emit('ok');
  } catch (error) {
    console.error(error);
  }
}

/** 处理取消 */
function handleCancel() {
  emit('update:visible', false);
}
</script>

<template>
  <a-modal :title="isEdit ? '编辑源数据' : '新建源数据'" :visible="visible" @ok="handleOk" @cancel="handleCancel">
    <a-form :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
      <a-form-item label="数据源名称">
        <a-input v-model:value="formState.name" />
      </a-form-item>
      <a-form-item label="数据源类型">
        <a-input v-model:value="formState.type" />
      </a-form-item>
      <a-form-item label="描述">
        <a-textarea v-model:value="formState.description" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
